//
// pipes_UNIX.cpp
// libprotea
// Tools Library for the Protea Project / OS pipe functionality, specific to UNIX
// Copyright (C) 2003, 2004, 2005 eXegeSys, Inc.
// Copyright (C) Bruce A. James
//
// This program is part of the Protea Project.
//
// The Protea Project is free software; you can redistribute it and/or modify it 
// under the terms of the GNU General Public License as published by the 
// Free Software Foundation, either version 3 of the License, or (at your 
// option) any later version.
//
// The Protea Project is distributed in the hope that it will be useful, but 
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
// for more details.
// 
// You should have received a copy of the GNU General Public License along 
// with this program.  If not, see <http://www.gnu.org/licenses/>.
// 
// Please send correspondence to:
// 
// theproteaproject@gmail.com
//

#include "../OS_defines.h"
#ifdef OS_UNIX

#include "../defines.h"
#include "pipes.h"
#include "../AppHandler/AppInterface.h"
#include "socket.h"

XCPipeTransport* XCPipeTransport::Create() {
	INFUNC( XCPipeTransport::Create, myapp )

	PORT_HANDLE in_pipes[2];
	PORT_HANDLE out_pipes[2];

	int result;

	result = pipe( in_pipes );
	if (result == -1)
		RAISEOSERROR();

	result = pipe( out_pipes );
	if (result == -1)
		RAISEOSERROR();

	mPipes[ TOOL_PIPE_READ ] = in_pipes[ 0 ];
	mPipes[ TOOL_PIPE_WRITE ] = out_pipes[ 1 ];

	myapp->ToolsTrace( TRC_TRAFFIC, TLV_HIGH, "Pipe create: in=%ld, out=%ld", mPipes[ TOOL_PIPE_READ ], mPipes[ TOOL_PIPE_WRITE ] );
	OUTFUNCRET( new XCPipeTransport( myapp, out_pipes[0], in_pipes[1], myowner ) );
};

int XCPipeTransport::Send( const void* data, int size ) {
	INFUNC( XCPipeTransport::Send, myapp )

	int result;

	if (size == -1)
		size = strlen( (const char*)data );

	result = write( mPipes[ TOOL_PIPE_WRITE ], data, size );
	if (result == -1)
		RAISEOSERROR();

	OUTFUNCRET( result );
};

int XCPipeTransport::Recv( void* data, int size ) {
	INFUNC( XCPipeTransport::Recv, myapp )

	int result;

	result = read( mPipes[ TOOL_PIPE_READ ], data, size );
	if (result == -1)
		RAISEOSERROR();

	OUTFUNCRET( result );
};

int XCPipeTransport::Close() {
	close( mPipes[ TOOL_PIPE_READ ] );
	close( mPipes[ TOOL_PIPE_WRITE ] );
	return 0;
};

#endif // OS_UNIX
